import { useAPIUtils } from "@/components/APIUtilsProvider";
import EmptyListPlaceholder from "@/components/EmptyListPlaceHolder";
import { moreModals } from "@/components/moreModals";
import PageLayout from "@/components/PageLayout";
import RenderIf from "@/components/RenderIf";
import When from "@/components/When";
import {
  Box,
  Button,
  Center,
  Divider,
  Flex,
  Group,
  Pagination,
  Paper,
  Popover,
  Select,
  Table,
  Text,
  TextInput,
} from "@mantine/core";
import { DateTimePicker } from "@mantine/dates";
import { useForm } from "@mantine/form";
import { modals } from "@mantine/modals";
import { IconSearch } from "@tabler/icons-react";
import dayjs from "dayjs";
import { useState } from "react";
import { useImmer } from "use-immer";
import StatusBadge from "./StatusBadge";
export default function OrderList() {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const [pagingCondition, setPagingCondition] = useImmer({
    orderId: "",
    status: "",
    start: dayjs().subtract(7, "days").toDate(),
    end: new Date(),
    receiver: "",
    pageIndex: 0,
    pageSize: 10,
  });

  const searchForm = useForm({
    mode: "uncontrolled",
    initialValues: {
      orderId: "",
      status: "",
      start: dayjs().subtract(7, "days").toDate(),
      end: new Date(),
      receiver: "",
    },
    validate: {},
  });

  const search = (values) => {
    tanstackInvalidate("/api/admin/orders");
    setPagingCondition({
      ...values,
      pageSize: pagingCondition.pageSize,
      pageIndex: 0,
    });
  };

  const confirmSecondSellerPaid = async (id) => {
    await restPUT(`/api/admin/orders/${id}?action=CONFIRM_SECOND_SELLER_PAID`);
    tanstackInvalidate("/api/admin/orders");
    tanstackInvalidate(`/api/admin/orders/${id}`);
  };

  const makeDelivery = async (id, { deliveryNo, deliveryVendorId }) => {
    await restPUT(`/api/admin/orders/${id}?action=MAKE_DELIVERY`, {
      deliveryNo,
      deliveryVendorId,
    });
    tanstackInvalidate("/api/admin/orders");
    tanstackInvalidate(`/api/admin/orders/${id}`);
  };

  const orderQuery = tanstackQuery("/api/admin/orders", {
    ...pagingCondition,
    category: pagingCondition.status ? pagingCondition.status : "",
    start: dayjs(pagingCondition.start).format("YYYY-MM-DDTHH:mm:ss"),
    end: dayjs(pagingCondition.end).format("YYYY-MM-DDTHH:mm:ss"),
    pageNo: pagingCondition.pageIndex,
    pageSize: pagingCondition.pageSize,
  });

  const totalPages = orderQuery.data?.totalPages;
  const rows = orderQuery.data?.content.map((order, index) => (
    <Table.Tr key={index}>
      <Table.Td>
        <Text>{index + 1}</Text>
      </Table.Td>
      <Table.Td>
        <Text>{order.id}</Text>
      </Table.Td>
      <Table.Td>
        <Text>{`${order.productName}(x${order.quantity})`}</Text>
      </Table.Td>
      <Table.Td>
        <Text>{order.buyer.nickname}</Text>
      </Table.Td>
      <Table.Td>
        <Text>{order.receiverName}</Text>
      </Table.Td>
      <Table.Td>{dayjs(order.createdAt).format("YYYY/MM/DD HH:mm")}</Table.Td>
      <Table.Td>
        <StatusBadge status={order.status} />
      </Table.Td>
      <Table.Td>
        <Group>
          <RenderIf auth="OrderRelated">
            <Button
              size="xs"
              onClick={() =>
                moreModals.openDefaultConfirmModal({
                  title: `点击确定代表您收到了来自[${order.secondSeller.nickname}]的货款${order.headQuarterPrice}元`,
                  onConfirm: () => {
                    confirmSecondSellerPaid(order.id);
                  },
                })
              }
              disabled={!order.actions?.includes("CONFIRM_SECOND_SELLER_PAID")}
            >
              确认收款
            </Button>
            <Button
              size="xs"
              onClick={() =>
                openMakeDeliveryModal({
                  onConfirm: (values) => makeDelivery(order.id, values),
                })
              }
              disabled={!order.actions?.includes("MAKE_DELIVERY")}
            >
              发货
            </Button>
          </RenderIf>
          <Button
            variant="subtle"
            size="xs"
            onClick={() => window.open(`./orders/${order.id}`, "_blank")}
          >
            详情
          </Button>
          <OrderPopover orderData={order} />
        </Group>
      </Table.Td>
    </Table.Tr>
  ));

  return (
    <PageLayout title={"订单管理"}>
      <form onSubmit={searchForm.onSubmit(search)}>
        <Flex
          mih={50}
          mb={44}
          gap="md"
          justify="flex-end"
          align="flex-end"
          direction="row"
          wrap="wrap"
        >
          <DateTimePicker
            description="时间开始"
            {...searchForm.getInputProps("start")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />
          <DateTimePicker
            description="时间结束"
            {...searchForm.getInputProps("end")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />

          <Select
            description="状态"
            {...searchForm.getInputProps("status")}
            placeholder="默认全部"
            clearable
            data={[
              { label: "等待买家付款", value: "CREATED" },
              { label: "等待经营店铺付款", value: "BUYER_PAID" },
              { label: "等待管理店铺付款", value: "FIRST_SELLER_PAID" },
              { label: "等待发货", value: "SECOND_SELLER_PAID" },
              { label: "运输中", value: "DELIVERING" },
              { label: "已完成", value: "RECEIVED" },
              { label: "已取消", value: "CANCELLED" },
            ]}
            renderOption={({ option }) => <StatusBadge status={option.value} />}
            w={200}
          />
          <TextInput
            description="收货人姓名"
            clearable
            placeholder="请输入收货人姓名"
            {...searchForm.getInputProps("receiver")}
            w={200}
          />
          <TextInput
            description="单号"
            clearable
            {...searchForm.getInputProps("orderId")}
            placeholder="请输入单号"
            w={200}
          />
          <Button type="submit" rightSection={<IconSearch size={14} />}>
            搜索
          </Button>
        </Flex>
      </form>

      <When condition={rows?.length > 0}>
        <Paper p={"md"}>
          <Table verticalSpacing={"sm"}>
            <Table.Thead>
              <Table.Tr>
                <Table.Th w={"3%"}></Table.Th>
                <Table.Th w={"10%"}>单号</Table.Th>
                <Table.Th w={"20%"}>品名</Table.Th>
                <Table.Th w={"10%"}>买家</Table.Th>
                <Table.Th w={"10%"}>收货人姓名</Table.Th>
                <Table.Th w={"10%"}>时间</Table.Th>
                <Table.Th w={"15%"}>状态</Table.Th>
                <Table.Th>操作</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>{rows}</Table.Tbody>
          </Table>
        </Paper>
        <Center mt={40}>
          <Pagination
            total={totalPages}
            value={pagingCondition.pageIndex + 1}
            onChange={(e) => {
              setPagingCondition({ ...pagingCondition, pageIndex: e - 1 });
            }}
          />
        </Center>
      </When>
      <When condition={rows?.length == 0}>
        <EmptyListPlaceholder />
      </When>
    </PageLayout>
  );
}

function OrderPopover({ orderData }) {
  const [opened, setOpened] = useState(false);

  return (
    <Popover
      opened={opened}
      onClose={() => setOpened(false)}
      position="left"
      width={360}
      withArrow
    >
      <Popover.Target>
        <Button variant="subtle" size="xs" onClick={() => setOpened(!opened)}>
          概要
        </Button>
      </Popover.Target>
      <Popover.Dropdown style={{ padding: "16px", lineHeight: "1.6" }}>
        <Text weight={500} size="sm" style={{ marginBottom: "8px" }}>
          {`订单概要(${orderData.id})`}
        </Text>
        <Divider my="sm" />
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>状态：</strong>
          <StatusBadge status={orderData.status} />
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>创建时间：</strong>
          {dayjs(orderData.createdAt).format("YYYY/MM/DD HH:mm")}
        </Text>
        <Divider mb="sm" />

        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>单价：</strong>¥{orderData.unitPrice.toFixed(2)}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>数量：</strong>
          {orderData.quantity}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>总价：</strong>¥{orderData.totalPrice.toFixed(2)}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>总积分：</strong>
          {orderData.totalPv}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>总部应收款：</strong>¥{orderData.headQuarterPrice.toFixed(2)}
        </Text>
        <Divider my="sm" />
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>收货人姓名：</strong>
          {orderData.receiverName}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>省市区：</strong>
          {orderData.receiverDistrict}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>收货地址：</strong>
          {orderData.receiverAddress}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>收货人电话：</strong>
          {orderData.receiverPhone}
        </Text>
        <Divider my="sm" />
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>买家：</strong>
          {orderData.buyer.nickname}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>经营店铺：</strong>
          {orderData.firstSeller.nickname}
        </Text>
        <Text size="sm" style={{ marginBottom: "6px" }}>
          <strong>管理店铺：</strong>
          {orderData.secondSeller.nickname}
        </Text>
      </Popover.Dropdown>
    </Popover>
  );
}

function openMakeDeliveryModal(props) {
  modals.open({
    title: "请填写运单信息",
    centered: true,
    children: <MakeDeliveryForm onConfirm={props.onConfirm} />,
    labels: { confirm: "确定", cancel: "取消" },
  });
}

function MakeDeliveryForm({ onConfirm }) {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const form = useForm({
    initialValues: {
      deliveryNo: "",
      deliveryVendorId: "",
    },

    validate: {
      deliveryNo: (value) =>
        /^[^\s]+$/.test(value) ? null : "请填写运单号，不能含有空格",
      deliveryVendorId: (value) =>
        /^[^\s]+$/.test(value) ? null : "请选择快递公司",
    },
  });

  const dictQuery = tanstackQuery(`/api/dictionaries/deliveryVendors`);

  const vendors = dictQuery.data
    ? Object.entries(dictQuery.data).map(([key, value]) => ({
        label: `${value.text}(${key})`,
        value: key,
      }))
    : [];

  return (
    <Box w="96%" mx="auto">
      <form
        onSubmit={form.onSubmit((values) => {
          onConfirm(values);
          modals.closeAll();
        })}
      >
        <Select
          label="快递公司"
          withAsterisk
          {...form.getInputProps("deliveryVendorId")}
          clearable
          data={vendors}
        />

        <TextInput
          withAsterisk
          label="快递单号"
          {...form.getInputProps("deliveryNo")}
        />

        <Group justify="flex-end" mt="md">
          <Button type="submit">Submit</Button>
        </Group>
      </form>
    </Box>
  );
}
